/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import classe.controlador.MaterialJpaController;
import classe.controlador.SetorJpaController;
import classe.controlador.exceptions.IllegalOrphanException;
import classe.controlador.exceptions.NonexistentEntityException;
import classe.entidade.Material;
import classe.entidade.Setor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pinheiro
 */
public class SetorRequisitante extends javax.swing.JFrame {

    /**
     * Creates new form SetorRequisitante
     */
    public SetorRequisitante() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaSetor = new javax.swing.JTable();
        editarSetor = new javax.swing.JButton();
        excluirSetor = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtSetorRequisitante = new javax.swing.JTextField();
        cadastrarSetor = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationByPlatform(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Setores cadastrados"));

        tabelaSetor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Descrição"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaSetor.setMinimumSize(new java.awt.Dimension(90, 160));
        tabelaSetor.setRowHeight(20);
        tabelaSetor.setSurrendersFocusOnKeystroke(true);
        jScrollPane1.setViewportView(tabelaSetor);
        tabelaSetor.getColumnModel().getColumn(0).setMinWidth(30);
        tabelaSetor.getColumnModel().getColumn(0).setPreferredWidth(30);
        tabelaSetor.getColumnModel().getColumn(0).setMaxWidth(30);

        editarSetor.setText("Editar");
        editarSetor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarSetorActionPerformed(evt);
            }
        });

        excluirSetor.setText("Excluir");
        excluirSetor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluirSetorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(editarSetor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(excluirSetor))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(editarSetor)
                    .addComponent(excluirSetor))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastrar setor"));

        jLabel2.setText("Nome do setor requisitante:");

        txtSetorRequisitante.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSetorRequisitanteActionPerformed(evt);
            }
        });

        cadastrarSetor.setText("Cadastrar");
        cadastrarSetor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastrarSetorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtSetorRequisitante, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cadastrarSetor)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtSetorRequisitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cadastrarSetor))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 668, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
    
    private void editarSetorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarSetorActionPerformed
         int linhaSelecionada = tabelaSetor.getSelectedRow();
         int idSetor = (int) tabelaSetor.getValueAt(linhaSelecionada, 0);
         String descricaoSetor = (String) tabelaSetor.getValueAt(linhaSelecionada, 1);
         
         EditarSetor janelaEditar = new EditarSetor(idSetor, descricaoSetor);
         janelaEditar.setVisible(true);
    }//GEN-LAST:event_editarSetorActionPerformed

    private void txtSetorRequisitanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSetorRequisitanteActionPerformed
       
    }//GEN-LAST:event_txtSetorRequisitanteActionPerformed

    private void cadastrarSetorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadastrarSetorActionPerformed
        cadastrarSetor();
        preencherTabela();
    }//GEN-LAST:event_cadastrarSetorActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        preencherTabela();
    }//GEN-LAST:event_formWindowActivated

    private void excluirSetorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excluirSetorActionPerformed
        int linha = tabelaSetor.getSelectedRow();
         int idSetor = (int) tabelaSetor.getValueAt(linha, 0);
         String descricaoSetor = (String) tabelaSetor.getValueAt(linha, 1);
         
         SetorJpaController daoSetor = new SetorJpaController();
        try {
            daoSetor.destroy(idSetor);
            preencherTabela();
        } catch (IllegalOrphanException ex) {
            Logger.getLogger(SetorRequisitante.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(SetorRequisitante.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_excluirSetorActionPerformed
    
    private void cadastrarSetor(){
        SetorJpaController daoSetor = new SetorJpaController();
        String setorRequisitante = txtSetorRequisitante.getText();
        Setor setor = new Setor();
        setor.setDescricao(setorRequisitante);
         daoSetor.create(setor);
         
    }
    
    private void preencherTabela() {
        limparTabela();

        SetorJpaController daoSetor = new SetorJpaController();
        ArrayList<Setor> arraySetor = new ArrayList<Setor>();

        try {

            // Captura todas os materiais
                arraySetor.addAll(daoSetor.findSetorEntities());
           
            
        } catch (PersistenceException e) {
            JOptionPane.showMessageDialog(rootPane, "Ocorreu um erro durante a conexão com o banco de dados.");
        }

        Iterator iterator = arraySetor.iterator();
        // Percorre todo o array dos setores
        while (iterator.hasNext()) {
            Setor setor = (Setor) iterator.next();
            Object[] linha;
            System.out.println(setor.getDescricao());
            // Adiciona os valores dos campos a variável do tipo objeto "linha"
            // que será usada para preencher a tabela com as três colunas
            linha = new Object[]{setor.getId(),
                setor.getDescricao().toUpperCase()};
                

            // Pega o modelo da tabela, e em seguida adiciona uma linha com os dados atribuidos a 
            // do tipo objeto acima
            DefaultTableModel catalogoModel = (DefaultTableModel) tabelaSetor.getModel();
            catalogoModel.addRow(linha);

        }

    }
    
    private void limparTabela() {
        DefaultTableModel setorModel = (DefaultTableModel) tabelaSetor.getModel();

        // Captura o número de linhas da tabela 
        int numeroLinhas = setorModel.getRowCount();

        // Remove as linhas da tabela
        for (int i = 0; i < numeroLinhas; i++) {
            setorModel.removeRow(0);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SetorRequisitante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SetorRequisitante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SetorRequisitante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SetorRequisitante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SetorRequisitante().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cadastrarSetor;
    private javax.swing.JButton editarSetor;
    private javax.swing.JButton excluirSetor;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelaSetor;
    private javax.swing.JTextField txtSetorRequisitante;
    // End of variables declaration//GEN-END:variables
}
